import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken, getUserInfo, getUserMenus, getAllowedPaths, getRoutesAdded } from '@/utils/auth' // get token from localStorage
import getPageTitle from '@/utils/get-page-title'
// import { buildRoutesFromPerms } from '@/utils/route'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/', '/dashboard'] // no redirect whitelist (首页公开)

// 路由前置守卫
router.beforeEach(async (to, from, next) => {
  // start progress bar
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)

  // determine whether the user has logged in
  const hasToken = getToken()

  console.log('路由守卫 - 目标路径:', to.path)
  console.log('路由守卫 - 来源路径:', from.path)
  console.log('路由守卫 - 是否有token:', hasToken)
  console.log('路由守卫 - token值:', hasToken)

  if (hasToken) {
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      console.log('路由守卫: 已登录，重定向到首页')
      next({ path: '/' })
      NProgress.done()
    } else {
      // 检查是否需要从localStorage恢复用户状态（页面刷新时）
      const hasGetUserInfo = store.getters.name
      const hasStoredUserInfo = getUserInfo()
      const hasStoredMenus = getUserMenus()
      const hasStoredAllowedPaths = getAllowedPaths()
      const hasStoredRoutesAdded = getRoutesAdded()

      console.log('路由守卫: 用户信息:', hasGetUserInfo)
      console.log('路由守卫: localStorage中的用户信息:', hasStoredUserInfo)
      console.log('路由守卫: localStorage中的菜单:', hasStoredMenus)
      console.log('路由守卫: localStorage中的允许路径:', hasStoredAllowedPaths)
      console.log('路由守卫: localStorage中的路由已添加状态:', hasStoredRoutesAdded)

      // 如果store中没有用户信息，但localStorage中有，则恢复状态
      if (!hasGetUserInfo && hasStoredUserInfo) {
        console.log('路由守卫: 从localStorage恢复用户信息')
        store.commit('user/SET_NAME', hasStoredUserInfo.name)
        store.commit('user/SET_AVATAR', hasStoredUserInfo.avatar)
      }

      // 如果store中没有菜单信息，但localStorage中有，则恢复状态
      if (store.state.user.menus.length === 0 && hasStoredMenus.length > 0) {
        console.log('路由守卫: 从localStorage恢复菜单信息')
        store.commit('user/SET_MENUS', hasStoredMenus)
      }

      // 如果store中没有允许路径，但localStorage中有，则恢复状态
      if (store.state.user.allowedPaths.length === 0 && hasStoredAllowedPaths.length > 0) {
        console.log('路由守卫: 从localStorage恢复允许路径')
        store.commit('user/SET_ALLOWED_PATHS', hasStoredAllowedPaths)
      }

      // 如果store中没有路由添加状态，但localStorage中有，则恢复状态
      if (!store.state.user.routesAdded && hasStoredRoutesAdded) {
        console.log('路由守卫: 从localStorage恢复路由添加状态')
        store.commit('user/SET_ROUTES_ADDED', hasStoredRoutesAdded)
      }

      if (!store.state.user.routesAdded) {
        try {
          // 确保有基本用户信息
          if (!hasGetUserInfo) {
            await store.dispatch('user/getInfo')
          }

          const menus = store.state.user.menus || []
          if (menus.length > 0) {
            // 根据后端视图路径映射到现有路由路径，构建允许访问清单
            const mapViewToRoute = (raw) => {
              if (!raw || typeof raw !== 'string') return null
              const view = raw.replace(/^@\//, '') // e.g. views/nested/xxx/index
              if (view === 'views/form/index') return '/settings/index'
              if (view === 'views/nested/user/index') return '/form/user'
              if (view === 'views/nested/consulting/index') return '/form/consulting'
              if (view === 'views/nested/org/index') return '/form/organization'
              if (view === 'views/nested/user/detail') return '/user/detail'
              if (view === 'views/nested/tokenStats/index') return '/statistics/token-stats'
              if (view === 'views/nested/trafficStats/index') return '/statistics/traffic-stats'
              // 文档管理路径映射
              if (view === 'views/nested/document/privacy') return '/document/privacy'
              if (view === 'views/nested/document/instructions') return '/document/instructions'
              if (view === 'views/nested/document/data') return '/document/data'
              if (view === 'views/nested/document/message') return '/document/message'
              const m = view.match(/^views\/nested\/([\w-]+)\/(index)$/)
              if (m) return `/nested/${m[1]}`
              return null
            }
            const allowedSet = new Set()
            menus.forEach(m => {
              const p = mapViewToRoute(m.path)
              if (p) allowedSet.add(p)
            })
            await store.dispatch('user/setAllowedPaths', Array.from(allowedSet))
          }
          await store.dispatch('user/setRoutesAdded', true)
          // 初始化完成后，无论是否有菜单权限，统一进入首页
          if (to.path === '/' || to.path === '/dashboard') {
            next()
          } else {
            next({ path: '/', replace: true })
          }
        } catch (e) {
          console.error('注入动态路由失败', e)
          next()
        }
      } else {
        // 检查是否有用户信息（包括从localStorage恢复的）
        const currentUserInfo = store.getters.name || getUserInfo()?.name
        console.log('路由守卫: 当前用户信息:', currentUserInfo)

        if (currentUserInfo) {
          console.log('路由守卫: 有用户信息，校验权限后允许访问')
          // 若目标路径不在允许列表，提示并停留当前页
          const allowed = store.state.user.allowedPaths || getAllowedPaths() || []
          const normalizedTo = to.path.replace(/\/index$/, '')

          // 检查是否为首页或仪表板（这些页面不需要权限检查）
          if (normalizedTo === '/' || normalizedTo === '/dashboard') {
            next()
            return
          }

          // 如果有权限列表且当前路径不在允许列表中，则提示无权限
          if (allowed.length > 0 && !allowed.includes(normalizedTo)) {
            console.log('路由守卫: 用户无权限访问', normalizedTo, '允许的路径:', allowed)
            Message.warning('无此访问权限，请联系高级管理员')
            NProgress.done()
            return next(false) // 明确中断导航，停留在当前页面
          }

          // 如果权限列表为空，表示权限系统未初始化或无任何权限，仅允许首页
          if (allowed.length === 0) {
            Message.warning('无此访问权限，请联系高级管理员')
            NProgress.done()
            return next(false)
          }

          next()
        } else {
          // 如果用户信息不存在，但有token，尝试获取用户信息
          try {
            // 这里应该调用获取用户信息的API
            // 假设我们有一个getUserInfo的action
            await store.dispatch('user/getInfo')
            console.log('路由守卫: 获取用户信息成功，允许访问')
            next()
          } catch (error) {
            // 获取用户信息失败，保留token并提示用户
            console.log('路由守卫: 获取用户信息失败，保留token')
            Message.error('获取用户信息失败，请检查网络或稍后重试')
            next() // 继续当前导航
            NProgress.done()
          }
        }
      }
    }
  } else {
    /* has no token*/
    console.log('路由守卫: 没有token')

    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      console.log('路由守卫: 白名单路径，直接访问')
      next()
    } else {
      // 没有token时，提示用户登录并停留在当前页面
      console.log('路由守卫: 无token访问受限页面，提示登录')
      Message.warning('请先登录后再访问此页面')
      NProgress.done()
      return next(false) // 阻止导航，停留在当前页面
    }
  }
})
// 路由后置守卫
router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
